<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="公司">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                       v-model="pageData.firm" @press-enter="huiche"/>
            </a-form-item>
            <a-form-item label="物料名称">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                       v-model="pageData.materialName" @press-enter="huiche"/>
            </a-form-item>
            <a-form-item label="领料单号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                       v-model="pageData.code1" @press-enter="huiche"/>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar class="gesture" :items="['查询', '新增', '删除', '打印二维码']" @add="addHandler"
                   @del="deleteHandler"
                   @select="selectHandler" @export="exports" @printQRCode="printQRCode">
          </Toolbar>
        </div>

      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>

    </template>
    <template #pageTabel>
      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple"
                       @grid-ready="gridReady" style="height: calc(100% - 45px)" :defaultColDef="defaultColDef"
                       class='ag-theme-alpine' :rowData="table.dataList" :localeText="localeText1"
                       :columnDefs="tc"></AgGridVuesCopys>
      <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
                       @change="PageSize" @page-size-change="change1"
                       style="justify-content: center" :page-size="size" :current="page"/>
    </template>

    <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 999 }" :mask-closable="false"
              unmount-on-close
              popup-container=".arco-tabs-content" :height="pageData.rHeight" :visible="pageData.showAdd" @ok="sideOk"
              :ok-loading="pageData.pageLoading" placement="bottom" @cancel="pageData.showAdd = false">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div style="min-width:1500px; overflow:auto;">
        <el-scrollbar>
          <a-form ref="formRef" layout="inline" :model="searchData" size="mini">
            <a-form-item label="公司" field="firmId" :rules="[{ required: true, message: '公司必填' }]">
              <a-cascader v-model="searchData.firmId" :options="pageData.firmGroupList" allow-clear
                          ref="casOb" @change="companyChange"
                          :class="{ bacClass: !(pageData.sideTitle != '新增五金领料单据') }" :title="pageData.title"
                          :disabled="pageData.sideTitle != '新增五金领料单据'" popup-container="html"/>
            </a-form-item>
            <a-form-item label="仓库类型" :rules="[{ required: true, message: '类型必填' }]" field="infoType">
              <a-select popup-container="html" @change="whChang" :style="{ width: '10rem' }"
                        v-model="searchData.infoType" :disabled="pageData.sideTitle == '修改五金领料单据'"
                        allow-clear class="bacClass">
                <a-option :value="0">化工仓</a-option>
                <a-option :value="1">染厂五金仓</a-option>
                <a-option :value="2">油品仓</a-option>
                <a-option :value="3">胶管仓</a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="仓库" :rules="[{ required: true, message: '仓库必填' }]" field="wh">
              <a-select popup-container="html" :style="{ width: '10rem' }" v-model="searchData.wh" allow-clear
                        :disabled="pageData.sideTitle != '新增五金领料单据'"
                        :class="{ bacClass: !(searchData.firmId == null || searchData.firmId == '' || pageData.sideTitle != '新增五金领料单据') }">
                <a-option v-for="item in whList" :value="item.id">
                  {{ item.warehouseName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="部门" :rules="[{ required: true, message: '部门必填' }]" field="depId">
              <a-cascader v-model="searchData.depId" :options="pageData.bmList" allow-clear ref="casc"
                          :class="{ bacClass: !(searchData.firmId == null || searchData.firmId == '') }"
                          :title="pageData.title1" :disabled="pageData.sideTitle == '修改五金领料单据'"
                          popup-container="html"/>
            </a-form-item>
            <a-form-item label="需求时间" :rules="[{ required: true, message: '需求时间' }]" field="requisitionTime">
              <a-date-picker popup-container="html" :style="{ width: '10rem' }" v-model="searchData.requisitionTime"
                             class="bacClass"/>
            </a-form-item>
          </a-form>

          <a-space style="margin-bottom:10px;">
            <a-button type="primary" @click="addLine" size="mini">新增</a-button>
            <a-button type="primary" @click="delLine" size="mini">删除</a-button>
          </a-space>
          <a-table stripe :bordered="true" :columns="tableColumnsWl" size="mini"
                   :row-selection="{ showCheckedAll: true, width: 50 }" v-model:selected-keys="selectedRowKeysWl"
                   :loading="table.tableLoading" :data="pageData.list" rowKey="id">
            <!-- <template #materialL="{ record }">
                <div style="width:100%;">
                    <a-select popup-container="html"  class="bacClass" :loading="loading" :allowClear="true" @search="handleSearch"
                        v-model="record.materialL" :filter-option="false" allow-search @focus="focusSel">
                        <a-option v-for="item in pageData.wlListL" :value="item['bigClassName']">{{
                            item['bigClassName']
                        }}
                        </a-option>
                    </a-select>
                </div>
            </template>
            <template #materialS="{ record }">
                <div style="width:100%;">
                    <a-select popup-container="html"  class="bacClass" :loading="loading1" :allowClear="true" @search="handleSearch1"
                        v-model="record.materialS" :filter-option="false" allow-search @focus="focusSel1">
                        <a-option v-for="item in pageData.wlListS" :value="item['subClassName']">{{
                            item['subClassName']
                        }}
                        </a-option>
                    </a-select>
                </div>
            </template> -->
            <template #materialCode="{ record }">
              <div style="width:100%;">
                <a-select popup-container="html" class="bacClass" :loading="loading" :allowClear="true"
                          @search="handleSearch2"
                          v-model="record.materialCode" :filter-option="false" allow-search
                          @focus="focusSel2(record, 1)" @change="changeBh(record, record.materialCode)">
                  <a-option v-for="item in pageData.wlList1" :value="item['materialCode']">{{
                      item['materialCode']
                    }}
                  </a-option>
                </a-select>
              </div>
            </template>
            <template #materialName="{ record }">
              <div style="width:100%;">
                <a-select popup-container="html" class="bacClass" :loading="loading" :allowClear="true"
                          @search="handleSearch2"
                          v-model="record.materialName" :filter-option="false" allow-search
                          @focus="focusSel2(record, 2)" @change="changeWl(record, record.materialName)">
                  <a-option v-for="item in pageData.wlList" :value="item['materialName']">{{
                      item['materialName']
                    }}
                  </a-option>
                </a-select>
              </div>
            </template>
            <template #grade="{ record }">
              <div style="width:100%;">
                <!-- <a-select popup-container="html"  placeholder="" class="bacClass" @focus="focusDj" v-model="record.grade" @change="changeDj(record)">
                    <a-option v-for="item in pageData.djList" :value="item['detailName']" >{{
                        item['detailName']
                    }}</a-option>
                </a-select> -->
                <a-input v-model="record.grade" class="input-demo bacClass" @change="changeDj(record)"/>
              </div>
            </template>

            <template #oldNewService="{ record }">
              <el-checkbox v-model="record.oldNewService" disabled :true-label="1"
                           :false-label="0"></el-checkbox>
            </template>
            <template #num="{ record }">
              <div style="width:100%;">
                <a-input-number v-model="record.num" class="input-demo bacClass" :min="0"
                                :max="10000000000"/>
              </div>
            </template>
          </a-table>
        </el-scrollbar>
      </div>
    </a-drawer>
    <a-modal v-model:visible="visible" @ok="handleOK" @cancel="handleCancel">
      <template #title>
        选择部门
      </template>
      <a-form ref="formRef1" layout="inline" :model="searchData" size="mini">
        <a-form-item label="部门" :rules="[{ required: true, message: '部门必填' }]" field="depId">
          <a-cascader v-model="searchData.depId" :options="pageData.bmList" allow-clear ref="casc"
                      :class="{ bacClass: !(searchData.firmId == null || searchData.firmId == '') }"
                      :title="pageData.title1" popup-container="html"/>

        </a-form-item>
        <!-- <a-form-item label="组别" field="groupId">
                            <a-select popup-container="html"  :style="{ width: '15rem' }" @change="companyChange" v-model="searchData.groupId" allow-clear
                                @focus="foucusUseFrim(3)">
                                <a-option v-for="item in pageData.zuList" :value="item.id">
                                    {{ item['zu'] }}
                                </a-option>
                            </a-select>
                        </a-form-item> -->
      </a-form>
    </a-modal>
    <a-modal :visible="visible2" @ok="handleOk" @cancel="visible2 = false" okText="打印" cancelText="关闭"
             unmountOnClose>
      <template #title> 打印二维码</template>
      <div id="lllist" style="height: 500px;">
        <div v-for="(item, index) in qrDataList" :key="index" style="display: inline-block;margin-bottom: 10px;">
          <QrcodeVue :value="item['code1']"></QrcodeVue>
          <div style="display: inline-block; vertical-align: top; margin-left: 15px; width: 250px">
            <span>领料单号: {{ decodeURI(item['code']) }}</span>
            <br/>
          </div>
        </div>

      </div>
    </a-modal>
    <a-modal fullscreen v-model:visible="visibleYl" :on-before-ok="handleOks" @cancel="handleCancels">
      <template #title>库存</template>
      <whTable :ref="whTbRef" :whId="whIds" :frimId="frimIds" :urlSelect="urlSelects"
               @getRowData="getRowDatas"></whTable>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
import {post} from '@/api/http'
import {useTable, useRowKey, useTableColumn, usePagination, useRowSelection} from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import {ref, reactive, onMounted, toRefs} from 'vue'
import Toolbar from '@/components/Toolbar.vue';
import {Button, Form, Message, Modal} from '@arco-design/web-vue';
import {FormInstance} from '@arco-design/web-vue/es/form';
import {baseURL} from '@/api/axios.config'
import axios from "axios";
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue';
import {slicing} from '@/utils/caseFrimAndSecRig'
import WHStore from '@/store/modules/wh'
import WHService from "@/service/wh"
import whTable from './wjcKcSelect.vue'
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import printJS from 'print-js'
import QrcodeVue from 'qrcode.vue'
import {pagingList} from '@/api/paging'
// 引入
;
import {localeText} from '@/api/aggridZw'
import {keyBy} from 'lodash';

interface HardwarePickList {
  "id": any,
  firm: any
  "firmId": any,
  "warehouseId": any,
  "warehouseName": string | undefined,
  "depId": any,
  "department": any,
  "materialL": any,
  "materialM": any,
  "materialS": any,
  "materialCode": any,
  "materialName": any,
  "num": any,
  "unit": any,
  "infoState": any,
  "obsoleteState": any,
  "createName": string | undefined,
  "createTime": string | undefined,
  "updateName": string | undefined,
  "updateTime": string | undefined,
  firmTypeId: any
  totalNum: any
  grade: any
}

export default {
  name: "HardwarePickList2",

  setup() {

    const casc = ref()

    const total = ref(0);
    const page = ref(1);
    const size = ref(10);
    const searchData = reactive<{
      whTypeName: string,
      firmId: any,
      wh: string,
      firm: string,
      firmTypeId: any,
      department: any,
      depId: any,
      groupId: any,
      groupName: any,
      createName: any,
      createTime: any,
      requisitionTime: any,
      infoType: any
    }>({
      whTypeName: '',
      firmId: null,
      wh: '',
      firm: '',
      firmTypeId: null,
      department: '',
      depId: null,
      groupId: null,
      groupName: '',
      createName: "",
      createTime: "",
      requisitionTime: "",
      infoType: null
    })
    const whStore = WHStore()
    whStore.getWhTypeList()

    function PageSize(val: any) {
      page.value = val
      doRefresh();
    }

    function change1(val: any) {
      size.value = val
      doRefresh();
    }

    const headerShow = ref<boolean>(true)

    function doRefresh() {

      pageData.pageLoading = true
      post({
        url: "dwWms/dwMetalsRequisitionForm/getPage",
        data: {
          page: page.value,
          size: size.value,
          deleteState: "0",
          materialName: pageData.materialName,
          firm: pageData.firm,
          code: pageData.code1
        },
      })
          .then(({data, code}: any) => {

            if (code === 200) {
              // data.list.forEach(function (o: any) {
              //     getTotalNum(o)
              // })
              table.handleSuccess(data.list);

              // 查询方法改

              gridOption.value.setRowData(data.list)


              total.value = data.total;
            }
          })
          .catch(console.log).finally(() => {
        pageData.pageLoading = false
      })
    }

    const {selectedRowKeys, onSelectionChange} = useRowSelection();
    const selectedRowKeysWl = ref()
    const pagination = usePagination(doRefresh);
    const table = useTable();
    const rowKey = useRowKey("id");
    const tableColumns = useTableColumn([
      {
        title: "领料单号",
        key: "code",
        dataIndex: "code",
        width: 150
      },
      {
        title: "公司",
        key: "firm",
        dataIndex: "firm",
        width: 150
      },

      {
        title: "部门",
        key: "department",
        dataIndex: "department",
        width: 150
      },
      {
        title: "发料仓库",
        key: "warehouseName",
        dataIndex: "warehouseName",
        width: 150
      },
      {
        title: "物料大类",
        key: "materialL",
        dataIndex: "materialL",
        width: 150,

      },
      {
        title: "物料小类",
        key: "materialS",
        dataIndex: "materialS",
        width: 150
      },
      {
        title: "物料编号",
        key: "materialCode",
        dataIndex: "materialCode",
        width: 150
      },
      {
        title: "物料名称",
        key: "materialName",
        dataIndex: "materialName",
        width: 150
      },
      // {
      //     title: "批次",
      //     key: "grade",
      //     dataIndex: "grade",
      //     width: 150
      // },
      {
        title: "库存数量",
        key: "totalNum",
        dataIndex: "totalNum",
        width: 150
      },
      {
        title: "数量",
        key: "num",
        dataIndex: "num",
        width: 150
      },
      {
        title: "单位",
        key: "unit",
        dataIndex: "unit",
        width: 150
      },
      {
        title: "需求时间",
        key: "requisitionTime",
        dataIndex: "requisitionTime",
        width: 150
      },


      {
        title: "创建人",
        key: "createName",
        dataIndex: "createName",
        width: 150
      },
      {
        title: "创建时间",
        key: "createTime",
        dataIndex: "createTime",
        width: 200
      },
      {
        title: "最后修改人",
        key: "updateName",
        dataIndex: "updateName",
        width: 150
      },
      {
        title: "最后修改时间",
        key: "updateTime",
        dataIndex: "updateTime",
        width: 200
      },
      {
        title: "处理状态",
        key: "infoState",
        dataIndex: "infoState",
        width: 150,
        fixed: 'right',
        slotName: 'infoState',
      },

      {
        title: '操作',
        key: "id",
        slotName: 'act',
        width: 150, fixed: 'right'
      }
    ]);

    const tableColumnsWl = useTableColumn([
      // {
      //     title: "部门",
      //     key: "department",
      //     dataIndex: "department",
      //     width: 150
      // },
      {
        title: "物料大类",
        key: "materialL",
        dataIndex: "materialL",
        width: 150,
        slotName: 'materialL',
      },
      {
        title: "物料小类",
        key: "materialS",
        dataIndex: "materialS",
        width: 150,
        slotName: 'materialS',
      },
      {
        title: "物料编号",
        key: "materialCode",
        dataIndex: "materialCode",
        width: 150,
        slotName: 'materialCode'
      },
      {
        title: "物料名称",
        key: "materialName",
        dataIndex: "materialName",
        width: 150,
        slotName: 'materialName'
      },
      // {
      //     title: "批次",
      //     key: "grade",
      //     dataIndex: "grade",
      //     width: 150,
      //     slotName: 'grade'
      // },

      {
        title: "单位",
        key: "unit",
        dataIndex: "unit",
        width: 150,

      },

      {
        title: "规格",
        key: "specification",
        dataIndex: "specification",
        width: 150,
      },
      {
        title: "库存数量",
        key: "totalNum",
        dataIndex: "totalNum",
        width: 150,
        slotName: 'totalNum'
      },
      {
        title: "数量",
        key: "num",
        dataIndex: "num",
        width: 150,
        slotName: 'num'
      },
      {
        title: "以旧换新",
        key: "oldNewService",
        dataIndex: "oldNewService",
        width: 150,
        slotName: 'oldNewService'
      }
    ]);
    let tc: any[] = tableColumns.map((o) => {

      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed']
      }
      obj['width'] = '250px'
      if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj["lockPosition"] = "right"
        obj['width'] = '80px'
        obj['cellRenderer'] = {
          template: `
            <a-tag color="#ff7d00" class="gesture" @click="a" v-if="c==0">修改</a-tag>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            return {
              e: pageData.isEdit,
              a,
              c: props.params.data.infoState
            }
          }

        }
      }

      if (o.slotName === 'infoState') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj["lockPosition"] = "right"
        obj['width'] = '90px'
        obj['cellRenderer'] = {
          template: `
            <a-tag color="#ff7d00" v-if="params.data.infoState==0">{{ val }}</a-tag>
            <a-tag color="#ffb400" v-if="params.data.infoState==1">{{ val }}</a-tag>
            <a-tag color="green" v-if="params.data.infoState==2">{{ val }}</a-tag>
            <a-tag color="#f53f3f" v-if="params.data.infoState==3">{{ val }}</a-tag>`,
          setup(props: any) {
            let val = ref()
            if (props.params.data.infoState == 0) {
              val.value = '待处理'
            } else if (props.params.data.infoState == 1) {
              val.value = '已受理'
            } else if (props.params.data.infoState == 2) {
              val.value = '已完结'
            }

            return {
              val
            }
          }

        }
      }

      return obj
    })

    let a = [{
      showRowGroup: 'hide_def',
      "headerName": "",
      "checkboxSelection": true,
      "headerCheckboxSelection": true,
      "pinned": "left",
      "width": 50,
      resizable: false,
      filter: false,
      sortable: false,
      minWidth: 50,
      maxWidth: 50,
      lockPosition: "left",
    }]
    tc = a.concat(tc)
    const pageData = reactive<{
      showAdd: boolean,
      sideTitle: string,
      dropDownData: any,
      nameList: [],
      pageLoading: boolean,
      typeList: [],
      dropDownData1: any,
      rHeight: any,
      isEdit: boolean,
      firmGroupList: any[],
      wlList: any[],
      list: any[],
      wlListL: any[],
      wlListS: any[],
      bmList: any[],
      zuList: any[],
      firm: any,
      materialName: any,
      title: any,
      title1: any,
      wlList1: any[],
      djList: any[],
      code: any
      code1: any
    }>({
      nameList: [],
      showAdd: false,
      sideTitle: '新增五金领料单据',
      dropDownData: "",
      pageLoading: false,
      typeList: [],
      dropDownData1: "",
      rHeight: 0,
      isEdit: false,
      firmGroupList: [],
      wlList: [],
      list: [],
      wlListL: [],
      wlListS: [],
      bmList: [],
      zuList: [],
      firm: "",
      materialName: "",
      title: "",
      title1: "",
      wlList1: [],
      djList: [],
      code: "",
      code1: "",
    });

    //下拉框得到焦点
    const focusSel = () => {
      getBigClass({"bigClassName": "", deleteState: 0});
    }
    //下拉数据
    const options = ref<any>(pageData.wlListL);
    const loading = ref(false);
    const handleSearch = (value: any) => {
      if (value) {
        const ob = {bigClassName: value, deleteState: 0}
        loading.value = true;
        getBigClass(ob);
        options.value = pageData.wlListL;
        loading.value = false;
      } else {
        options.value = []
      }
    };

    //查询物料大类
    function getBigClass(val: any) {
      post({
        url: "dwPurchase/MaterialBigClass/getFieldValue",
        data: val
      }).then(({data, code}: any) => {
        if (code === 200) {
          pageData.wlListL = data;
        } else {
          Message.error({
            content: "查询失败！",
            duration: 5000,
          });
        }
      });
    }


    onMounted(() => {

      //弹出层的高
      if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight - 100;
      }
      window.addEventListener('resize', () => {
        pageData.rHeight = document.getElementsByClassName("arco-tabs-content")[0]?.clientHeight
        //弹出层的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight - 100;
        }
      })
    });
    //查询
    const selectHandler = () => {
      page.value = 1
      doRefresh();
    }
    const queryData = reactive({
      clothType: ""
    });
    const addHandler = () => {
      for (var key in searchData) {
        searchData[key] = "";
      }
      for (var key in dataForm) {
        dataForm[key] = "";
      }
      pageData.list = []
      getFirmGroup()
      pageData.showAdd = true
      pageData.sideTitle = '新增五金领料单据'


    }
    const dataForm: any = reactive({
      "id": undefined,
      "firmId": undefined,
      "warehouseId": undefined,
      "warehouseName": undefined,
      "depId": undefined,
      "department": undefined,
      "materialL": undefined,
      "materialM": undefined,
      "materialS": undefined,
      "materialCode": undefined,
      "materialName": undefined,
      "num": undefined,
      "unit": undefined,
      "infoState": undefined,
      "obsoleteState": undefined,
      "createName": undefined,
      "createTime": undefined,
      "updateName": undefined,
      "updateTime": undefined,
      firm: undefined,
      firmTypeId: undefined,
      totalNum: 0,
      // grade: ""
    })

    // 表格准备事件
    const gridOption = ref()
    const gridReady = (params: any) => {

      gridOption.value = params.api
    }


    let formRef = ref<FormInstance>()
    let formRef1 = ref<FormInstance>()
    const sideOk = () => {
      if (pageData.list.length == 0) {
        Message.warning({
          content: "请新增至少一条物料信息",
          duration: 5000,
        });
        return
      }
      formRef.value?.validate().then((err) => {
        if (!err) {


          //拿到仓库名称
          let list = whList.value.filter(function (o: any) {
            return o['id'] == searchData.wh
          })
          let warehouseName = ''
          if (list.length > 0) {
            warehouseName = list[0]['warehouseName']
          }
          let flag = false
          pageData.list.forEach(function (o: any) {
            o.infoType = searchData.infoType
            o.whTypeName = searchData.whTypeName
            o.firmId = searchData.firmId
            o.firm = searchData.firm
            o.firmTypeId = searchData.firmTypeId
            o['requisitionTime'] = searchData['requisitionTime']
            o.depId = searchData.depId
            o.groupId = searchData.groupId
            o.groupName = searchData.groupName
            o.createName = searchData.createName
            o.createTime = searchData.createTime
            o['warehouseName'] = warehouseName
            o['warehouseId'] = searchData.wh
            o['code'] = pageData.code
            // if (o["grade"] == "" || o["grade"] == undefined || o["grade"] == null || o["materialCode"] == "" || o["materialCode"] == undefined || o["materialCode"] == null) {
            //     flag = true
            // }

          })
          // if (flag) {
          //     Message.warning({
          //         content: "请将所有行的批次和物料填完！",
          //         duration: 5000,
          //     });
          //     return
          // }
          pageData.list.forEach(function (o: any) {
            if ((o['id'] + "").indexOf('add') != -1) {
              o['id'] = null
            }
          })
          pageData.pageLoading = true;
          if (pageData.sideTitle === "新增五金领料单据") {
            post({
              url: "/dwWms/dwMetalsRequisitionForm/add",
              data: pageData.list,
            }).then((res: any) => {
              if (res.code === 200) {
                formRef.value?.resetFields();
                pageData.showAdd = false;

                Message.success({
                  content: "新增成功",
                  duration: 5000,
                });
              } else {
                Message.error({
                  content: res.message,
                  duration: 5000,
                });
              }
              doRefresh();
            }).finally(() => {
              doRefresh();
              pageData.pageLoading = false
            })
          } else {
            post({
              url: "dwWms/dwMetalsRequisitionForm/update",
              data: pageData.list,
            }).then((res: any) => {
              if (res.code === 200) {
                formRef.value?.resetFields();
                pageData.showAdd = false;
                Message.success({
                  content: "修改成功",
                  duration: 5000,
                });

              } else {
                Message.error({
                  content: res.message,
                  duration: 5000,
                });
              }

            }).finally(() => {

              doRefresh();
              pageData.pageLoading = false
            })
          }
        }
      })
    }
    const deleteHandler = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选');
        return
      }

      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          pageData.pageLoading = true;
          post({
            url: 'dwWms/dwMetalsRequisitionForm/delete',
            data: gridOption.value.getSelectedRows().map((o: any) => {
              return o.id
            })
          }).then(({code, data}: any) => {
            if (code === 200) {
              Message.success({
                content: '删除成功',
                duration: 5000
              })
              pagination.page = 1
              doRefresh()

            } else {
              Message.error({
                content: '删除失败',
                duration: 5000
              })
            }

          }).finally(() => {
            pageData.pageLoading = false
          });
        }
      })
    }

    const editHandler = (record: HardwarePickList) => {
      selCxAll1({bigClassName: ""})
      getBigClass({bigClassName: ""})
      let type = record.infoType == 0 ? '化工仓' : record.infoType == 1 ? '染厂五金仓' : record.infoType == 2 ? '油品仓' : record.infoType == 3 ? '胶管仓' : ""
      whService.getWarhouseListByFirmId(record.firmId, type)
      whList.value = whService.whList.value

      searchData.wh = record['warehouseId']
      getFirmGroup()
      getBmGroup(record.firmId)
      pageData.code = record['code']
      //根据单号回显此单号的物料信息
      post({
        url: 'dwWms/dwMetalsRequisitionForm/getList',
        data: {code: record['code']}
      }).then(({code, data, message}: any) => {
        if (code === 200) {
          for (var key in record) {
            searchData[key] = record[key]
          }

          pageData.list = data
          // pageData.list.forEach(function (o: any) {
          //     getTotalNum(o)
          // })
          pageData.sideTitle = '修改五金领料单据'
          pageData.showAdd = true

        } else {
          Message.error({
            content: message,
            duration: 5000
          })
        }

      }).finally(() => {
        pageData.pageLoading = false
      });

    }


    //导出
    const exports = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选');
        return
      } else {
        let idList: any = []
        gridOption.value.getSelectedRows().forEach(function (o: any) {
          idList.push(o['id'])
        })
        //将表头拼接出来
        let head = "<th>编号</th><th>品牌名称</th><th>布类类型</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = table.dataList.filter(function (o) {
          return (gridOption.value.getSelectedRows().map((o: any) => {
            return o.id
          })).indexOf(o["id"]) !== -1;
        })
        let body = "";
        nowRow.forEach(function (o) {
          body += "<tr><td>" + o["brandCode"] + "</td>";
          body += "<td>" + o["brandName"] + "</td>";
          body += "<td>" + o["clothClass"] + "</td>";
          body += "<td>" + o["remark"] + "</td>";
          body += "<td>" + o["createName"] + "</td>";
          body += "<td>" + o["createTime"] + "</td>";
          body += "<td>" + o["updateName"] + "</td>";
          body += "<td>" + o["updateTime"] + "</td>";
          body += "</tr>";
        })
        tableToXlsx(head, '五金领料单据', body)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

      const a = document.createElement('a');
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
      a.download = filename;
      a.click();
      document.removeChild(a);
    }


    //下拉数据
    const options1 = ref<any>(pageData.wlListS);
    const loading1 = ref(false);
    const handleSearch1 = (value: any) => {
      if (value) {

        const ob = {
          bigClassName: value,
        }
        loading.value = true;
        selCxAll1(ob);
        options1.value = pageData.wlListS;
        loading1.value = false;
      } else {
        options1.value = []
      }
    };

    //下拉框查询 物料小类
    function selCxAll1(val: any) {
      post({
        url: "dwPurchase/MaterialSubClass/getFieldValue",
        data: val
      }).then(({data, code}: any) => {
        if (code === 200) {
          pageData.wlListS = data;
        } else {
          Message.error({
            content: "查询失败！",
            duration: 5000,
          });
        }
      });
    }

    //下拉框得到焦点
    const focusSel1 = () => {
      selCxAll1({"bigClassName": ""});
    }

    const handleChange = (_data: any) => {
      table.handleSuccess(_data);
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    const huiche = () => {
      doRefresh();
    }
    const localeText1: any = ref(localeText)
    let i = 0;
    //成分添加一行 点击新增按钮
    const addLine = () => {
      // searchData.depId = ''
      // searchData.department = ''
      // visible.value = true;
      searchData['department'] = slicing(casc.value?.selectViewValue[0].label)
      pageData.title1 = slicing(casc.value?.selectViewValue[0]['label'])
      //在这个数组前面添加一行
      // pageData.list.unshift({
      //     "id": "add" + (i++),
      //     "materialL": "",
      //     "materialS": "",
      //     "materialCode": "",
      //     "materialName": "",
      //     "num": "",
      //     depId: searchData.depId,
      //     department: searchData.department,
      //     // grade: "",
      //     totalNum: "",

      // })
      if (searchData.infoType == 0) {
        urlSelects.value = 'dwWms/dwChemicalsStockSummary/getPageMaterialSum'
      } else if (searchData.infoType == 1) {
        urlSelects.value = 'dwWms/dwIronwareStockSummary/getPageMaterialSum'
      } else if (searchData.infoType == 2) {
        urlSelects.value = 'dwWms/dwOilsStockSummary/getPageMaterialSum'
      } else if (searchData.infoType == 3) {
        urlSelects.value = 'dwWms/dwRubberStockSummary/getPageMaterialSum'
      }
      whIds.value = Number(searchData.wh)
      frimIds.value = Number(searchData.firmId)
      visibleYl.value = true
      nextTick(() => {
        whTbRef.value?.delWhList()
      })
    }

    //成分 删除
    const delLine = () => {

      if (selectedRowKeysWl.value.length === 0) {
        Message.error({
          content: '请先勾选',
          duration: 5000
        })
        return
      }
      pageData["list"] = pageData["list"].filter(function (o: any) {
        return selectedRowKeysWl.value.indexOf(o["id"]) === -1
      })

    }
    const whService = new WHService();
    const companyList: any = whService.companyList;
    const whTypeList = whService.whTypeList
    const whList = ref<any[]>([])
    let casOb = ref()
    // 公司下拉框 改变
    const companyChange = () => {
      searchData.wh = "";
      whService.getWarhouseListByFirmId(searchData.firmId, '五金仓')
      getBmGroup(searchData.firmId)
      setTimeout(function () {
        if (casOb.value.selectViewValue.length != 0) {
          pageData.title = slicing(casOb.value.selectViewValue[0]['label'])
          searchData.firm = slicing(casOb.value.selectViewValue[0]['label'])
        }
      }, 100)

    };
    const whChang = (e: any) => {
      let type = e == 0 ? '化工仓' : e == 1 ? '染厂五金仓' : e == 2 ? '油品仓' : e == 3 ? '胶管仓' : ""
      whService.getWarhouseListByFirmId(searchData.firmId, type)
      searchData.wh = ""
    }
    watch(() => whService.whList.value, (o, n) => {
      whList.value = whService.whList.value
    });
    //下拉数据
    const options2 = ref<any>(pageData.wlList);
    const handleSearch2 = (value: any) => {
      if (value) {

        const ob = {}
        if (nums == 1) {
          ob['materialCode'] = value
        } else {
          ob['materialName'] = value
        }
        loading.value = true;
        getWlName(ob);
        options2.value = pageData.wlListS;
        loading.value = false;
      } else {
        options2.value = []
      }
    };

    //查询物料名称
    function getWlName(val: any) {
      post({
        url: "dwPurchase/MaterialInfo/getFieldValueWms",
        data: val
      }).then(({data, code}: any) => {

        if (code === 200) {
          if (nums == 1) {
            pageData.wlList1 = data;
          } else {
            pageData.wlList = data;
          }

        } else {
          Message.error({
            content: "查询失败！",
            duration: 5000,
          });
        }
      });
    }

    let subClassName = ""
    let nums = 1
    //下拉框得到焦点
    const focusSel2 = (record: any, num: any) => {
      // subClassName = record.materialS
      if (num == 1) {
        getWlName({"materialCode": ""});
      } else {
        getWlName({"materialName": ""});
      }

      nums = num

    }

    //物料名称改变 拿到物料编号
    function changeWl(record: any, val: any) {
      let list2 = pageData.list.filter(function (o: any) {
        return (o['materialName'] == record['materialName'] && o['depId'] == record['depId'])
      })
      if (list2.length > 1) {
        record['materialName'] = ''
        record['materialCode'] = ''
        record['specification'] = ''
        Message.warning({
          content: '请不要重复选择物料！',
          duration: 5000,
        })
        return
      }

      let list = pageData.wlList.filter(function (o: any) {
        return o['materialName'] == val
      })
      if (list.length > 0) {
        record['materialCode'] = list[0]['materialCode']
        record['unit'] = list[0]['unit']
        record['specification'] = list[0]['specification']
        record['materialL'] = list[0]['materialL']
        record['materialS'] = list[0]['materialS']
      }
      getTotalNum(record)
    }

    //物料编号改变 拿到物料名称
    function changeBh(record: any, val: any) {
      let list2 = pageData.list.filter(function (o: any) {
        return (o['materialCode'] == record['materialCode'] && o['depId'] == record['depId'])
      })
      if (list2.length > 1) {
        record['materialName'] = ''
        record['materialCode'] = ''
        record['specification'] = ''
        Message.warning({
          content: '请不要重复选择物料！',
          duration: 5000,
        })
        return
      }

      let list = pageData.wlList1.filter(function (o: any) {
        return o['materialCode'] == val
      })
      if (list.length > 0) {
        record['materialName'] = list[0]['materialName']
        record['unit'] = list[0]['unit']
        record['specification'] = list[0]['specification']
        record['materialL'] = list[0]['materialL']
        record['materialS'] = list[0]['materialS']
      }
      getTotalNum(record)
    }

    function changeDj(record: any) {
      getTotalNum(record)
    }

    //拿到库存数量
    function getTotalNum(record: any) {
      post({
        url: 'dwWms/dwIronwareStockSummary/getGoodsStockNum',
        data: {
          materialCode: record['materialCode'],
          grade: record['grade'],
          warehouseId: record['warehouseId']
        },
      }).then(({code, data}) => {
        if (code === 200) {
          console.log(data);
          record['totalNum'] = data['totalNum']
        }
      })
    }

    //部门下拉框弹窗
    const visible = ref(false);
    const handleCancel = () => {
      visible.value = false;
    }
    const handleOK = () => {
      formRef1.value?.validate().then((err) => {
        if (!err) {
          // let list = pageData.bmList.filter(function (o: any) {
          //     return o['id'] == searchData['depId']
          // })
          // if (list.length > 0) {
          //     searchData['department'] = list[0]['department']
          // }

          searchData['department'] = slicing(casc.value.selectViewValue[0].label)
          pageData.title1 = slicing(casc.value.selectViewValue[0]['label'])
          //在这个数组前面添加一行
          pageData.list.unshift({
            "id": "add" + (i++),
            "materialL": "",
            "materialS": "",
            "materialCode": "",
            "materialName": "",
            "num": "",
            depId: searchData.depId,
            department: searchData.department,
            // grade: "",
            totalNum: "",

          })

          visible.value = false;
        }
      })
    }
    //   // 获取公司列表
    const getFirmGroup = () => {
      post({
        url: 'org/baCompany/getTreeCompanyByUser',
        data: {},
      }).then(({code, data}) => {
        if (code === 200) {
          pageData.firmGroupList = data
        }
      })
    }
    // 获取部门列表
    const getBmGroup = (val: any) => {
      post({
        url: 'org/baCompany/getDepartmentTree?companyId=' + val,
      }).then((result) => {
        if (result.code === 200) {
          pageData.bmList = result.data
        }
      })
    }

    //取到所有排纱下拉框
    function focusDj() {
      post({
        url: 'dict/dictTypeDetail/getListByCodeType?codeType=26',

      }).then((res: any) => {
        if (res.code == 200) {
          pageData.djList = res.data
        }
      })
    }

    const qrDataList: any = ref([])

    const visible2 = ref(false)

    const printQRCode = () => {
      qrDataList.value = []
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请勾选需要打印的数据')
        return
      }
      let row = gridOption.value.getSelectedRows()
      row.forEach(function (o: any) {
        let ob: any = {}
        ob['code'] = o['code']
        ob['code1'] = JSON.stringify({'code': o['code']})
        qrDataList.value.push(ob)
      })
      visible2.value = true


    }

    const handleOk = () => {
      printJS({
        printable: 'lllist',
        type: 'html',
        targetStyles: ['*'],
      })
      visible2.value = false
    }
    const whTbRef: any = ref()
    const whIds: any = ref(null)
    const frimIds: any = ref(null)
    const urlSelects: any = ref('')
    let whListRowData: any = []

    const getRowDatas = (e: any) => {
      whListRowData = e
    }
    const visibleYl = ref(false)
    const handleOks = () => {
      if (whListRowData.length == 0) {
        return false
      }
      whListRowData.forEach((e: any) => {
        e.depId = searchData.depId
        e.department = searchData.department
        e.materialL = e.majorCategory
        e.materialS = e.subCategory
      })
      pageData.list = whListRowData
      return true
    }
    const handleCancels = () => {
      visibleYl.value = false
    }
    const pagingList1: any = ref(pagingList)
    return {
      pagingList1,
      frimIds,
      handleCancels,
      handleOks,
      visibleYl,
      getRowDatas,
      urlSelects,
      whIds,
      whTbRef,
      handleOk,
      visible2,
      qrDataList,
      printQRCode,
      whChang,
      changeDj,
      focusDj,
      changeBh,
      casOb,
      casc,
      handleOK,
      formRef1,
      visible,
      handleCancel,
      changeWl,
      options2,
      handleSearch2,
      focusSel2,
      getWlName,
      getBigClass,
      whList,
      searchData,
      companyList,
      whTypeList,
      companyChange,
      addLine,
      delLine,
      huiche,
      localeText1,
      defaultColDef,
      tc,
      total,
      PageSize,
      change1,
      page,
      size,
      editHandler,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      selectedRowKeysWl,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      selectHandler,
      exports,
      options,
      loading,
      handleSearch,
      focusSel,
      options1,
      loading1,
      handleSearch1,
      focusSel1,
      headerShow,
      handleChange,
      gridReady,
      tableColumnsWl,
    };
  },
  components: {Toolbar, PageTabelLayout, CorporateSectorCascader, QrcodeVue, whTable}
}
</script>
